package com.sq.imp.MyMenuManagers;

import com.sq.abstractClass.Text;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.sql.*;
import java.util.ArrayList;

public class DatabaseManager {
    private final Text textArea;
    private Connection connection;
    private final JFrame frame;
    private JTabbedPane resultTabbedPane;

    private JTextField hostField, portField, dbNameField, userField, passwordField;
    private String host, port, dbName, user, password;
    public JMenu dbMenu = new JMenu("数据库");
    public DatabaseManager(Text textArea, JFrame frame) {
        this.textArea = textArea;
        this.frame = frame;
        // 创建数据库菜单
        JMenuItem configItem = new JMenuItem("配置 MySQL 连接");
        JMenuItem runAllItem = new JMenuItem("运行记事本文本命令");
        JMenuItem runSelectedItem = new JMenuItem("运行记事本选中文本命令");
        JMenuItem saveSQLItem = new JMenuItem("保存 SQL 脚本");
        JMenuItem loadSQLItem = new JMenuItem("加载 SQL 脚本");

        dbMenu.add(configItem);
        dbMenu.add(runAllItem);
        dbMenu.add(runSelectedItem);
        dbMenu.add(saveSQLItem);
        dbMenu.add(loadSQLItem);

        configItem.addActionListener(e -> showConfigWindow());
        runAllItem.addActionListener(e -> runSQLCommands(textArea.getText()));
        runSelectedItem.addActionListener(e -> {
            String selectedText = textArea.getSelectedText();
            if (selectedText != null) {
                runSQLCommands(selectedText);
            } else {
                JOptionPane.showMessageDialog(frame, "请先选择文本！", "错误", JOptionPane.ERROR_MESSAGE);
            }
        });
        saveSQLItem.addActionListener(e -> saveSQLScript());
        loadSQLItem.addActionListener(e -> loadSQLScript());
    }

    public void showConfigWindow() {
        JDialog configDialog = new JDialog(frame, "配置 MySQL 连接", true);
        configDialog.setSize(300, 250);
        configDialog.setLayout(new GridLayout(6, 2, 10, 10));

        configDialog.add(new JLabel("主机:"));
        hostField = new JTextField("localhost");
        configDialog.add(hostField);

        configDialog.add(new JLabel("端口:"));
        portField = new JTextField("3306");
        configDialog.add(portField);

        configDialog.add(new JLabel("数据库:"));
        dbNameField = new JTextField("mysql");
        configDialog.add(dbNameField);

        configDialog.add(new JLabel("用户名:"));
        userField = new JTextField("root");
        configDialog.add(userField);

        configDialog.add(new JLabel("密码:"));
        passwordField = new JTextField("root");
        configDialog.add(passwordField);

        JButton connectButton = new JButton("连接");
        connectButton.addActionListener(e -> {
            host = hostField.getText();
            port = portField.getText();
            dbName = dbNameField.getText();
            user = userField.getText();
            password = passwordField.getText();

            try {
                connection = DriverManager.getConnection(
                        "jdbc:mysql://" + host + ":" + port + "/" + dbName, user, password);
                JOptionPane.showMessageDialog(configDialog, "连接成功！");
                configDialog.dispose();
            } catch (SQLException ex) {
                JOptionPane.showMessageDialog(configDialog, "连接失败：" + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
            }
        });
        configDialog.add(connectButton);

        JButton resetConnectButton = new JButton("重置连接");
        resetConnectButton.addActionListener(e -> resetConnection());
        configDialog.add(resetConnectButton);

        configDialog.setVisible(true);
    }

    private void resetConnection() {
        if (connection != null) {
            try {
                connection.close();
                connection = null;
                JOptionPane.showMessageDialog(frame, "连接已重置！", "成功", JOptionPane.INFORMATION_MESSAGE);
            } catch (SQLException ex) {
                JOptionPane.showMessageDialog(frame, "重置连接失败：" + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
            }
        } else {
            JOptionPane.showMessageDialog(frame, "当前没有活动的连接！", "提示", JOptionPane.INFORMATION_MESSAGE);
        }
    }

    public void runSQLCommands(String sql) {
        if (connection == null) {
            JOptionPane.showMessageDialog(frame, "请先配置 MySQL 连接！", "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }

        JFrame resultWindow = null;

        try (Statement statement = connection.createStatement()) {
            String[] commands = sql.split(";");
            for (String command : commands) {
                command = command.trim();
                if (command.isEmpty()) continue;

                if (command.toUpperCase().startsWith("USE ")) {
                    statement.execute(command);
                    showTextResult("数据库切换成功：" + command, command);
                } else {
                    try {
                        boolean isQuery = command.toLowerCase().startsWith("select") || command.toLowerCase().startsWith("show");
                        if (resultWindow == null) {
                            resultWindow = new JFrame("执行结果");
                            resultWindow.setSize(800, 600);
                            resultWindow.setLayout(new BorderLayout());
                            resultTabbedPane = new JTabbedPane();
                            resultWindow.add(resultTabbedPane, BorderLayout.CENTER);
                            resultWindow.setVisible(true);
                        }
                        if (isQuery) {
                            ResultSet resultSet = statement.executeQuery(command);
                            showResultSet(resultSet, command);
                        } else {
                            int rowsAffected = statement.executeUpdate(command);
                            showTextResult("操作成功！受影响的行数：" + rowsAffected, command);
                        }
                    } catch (SQLException ex) {
                        showTextResult("执行失败：" + ex.getMessage(), command);
                    }
                }
            }
        } catch (SQLException ex) {
            showTextResult("执行失败：" + ex.getMessage(), sql);
        }
    }

    private void showResultSet(ResultSet resultSet, String sql) throws SQLException {
        ResultSetMetaData metaData = resultSet.getMetaData();
        int columnCount = metaData.getColumnCount();
        String[] columnNames = new String[columnCount];
        for (int i = 1; i <= columnCount; i++) {
            columnNames[i - 1] = metaData.getColumnName(i);
        }

        DefaultTableModel tableModel = new DefaultTableModel(columnNames, 0);
        while (resultSet.next()) {
            Object[] row = new Object[columnCount];
            for (int i = 1; i <= columnCount; i++) {
                row[i - 1] = resultSet.getObject(i);
            }
            tableModel.addRow(row);
        }

        JTable table = new JTable(tableModel);
        JScrollPane scrollPane = new JScrollPane(table);
        resultTabbedPane.addTab("查询结果 - " + sql.substring(0, Math.min(sql.length(), 30)), scrollPane);
    }

    private void showTextResult(String result, String sql) {
        JTextArea textArea = new JTextArea(result);
        textArea.setEditable(false);
        JScrollPane scrollPane = new JScrollPane(textArea);
        resultTabbedPane.addTab("执行结果 - " + sql.substring(0, Math.min(sql.length(), 30)), scrollPane);
    }

    public void runSelectedSQLCommand() {
        String selectedText = textArea.getSelectedText();
        if (selectedText != null) {
            runSQLCommands(selectedText);
        } else {
            JOptionPane.showMessageDialog(frame, "请先选择文本！", "错误", JOptionPane.ERROR_MESSAGE);
        }
    }

    public void saveSQLScript() {
        try {
            UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
        } catch (Exception e) {
            e.printStackTrace();
        }
        JFileChooser fileChooser = new JFileChooser();
        int result = fileChooser.showSaveDialog(frame);
        if (result == JFileChooser.APPROVE_OPTION) {
            try {
                java.nio.file.Files.write(fileChooser.getSelectedFile().toPath(), textArea.getText().getBytes());
                JOptionPane.showMessageDialog(frame, "脚本已保存！", "成功", JOptionPane.INFORMATION_MESSAGE);
            } catch (Exception e) {
                JOptionPane.showMessageDialog(frame, "保存失败：" + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
            }
        }
    }

    public void loadSQLScript() {
        try {
            UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
        } catch (Exception e) {
            e.printStackTrace();
        }
        JFileChooser fileChooser = new JFileChooser();
        int result = fileChooser.showOpenDialog(frame);
        if (result == JFileChooser.APPROVE_OPTION) {
            try {
                String content = new String(java.nio.file.Files.readAllBytes(fileChooser.getSelectedFile().toPath()));
                textArea.setText(content);
                JOptionPane.showMessageDialog(frame, "脚本已加载！", "成功", JOptionPane.INFORMATION_MESSAGE);
            } catch (Exception e) {
                JOptionPane.showMessageDialog(frame, "加载失败：" + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
            }
        }
    }
}